import {
  getQuestions,
  createQuestion,
  updateQuestion,
  deleteQuestion,
  batchDeleteQuestions,
} from "../model/question.js";

// 查询题库列表
export async function getQuestionList(ctx) {
  const { type = "", keyword = "", pagenum = 1, pagesize = 10 } = ctx.query;
  const result = await getQuestions({
    type,
    keyword,
    pagenum: Number(pagenum),
    pagesize: Number(pagesize),
  });
  ctx.body = result;
}

// 新建题目
export async function postQuestion(ctx) {
  const data = ctx.request.body;
  // options 需转为字符串存储，且多选题答案需转为字符串
  if (Array.isArray(data.options)) data.options = JSON.stringify(data.options);
  // 多选题答案如为数组，转为字符串
  if (data.type === '多选题' && Array.isArray(data.answer)) {
    data.answer = data.answer.join('');
  }
  ctx.body = await createQuestion(data);
}

// 编辑题目
export async function putQuestion(ctx) {
  const id = ctx.params.id;
  const data = ctx.request.body;
  if (Array.isArray(data.options)) data.options = JSON.stringify(data.options);
  ctx.body = await updateQuestion(id, data);
}

// 删除题目
export async function deleteQuestionById(ctx) {
  const id = ctx.params.id;
  ctx.body = await deleteQuestion(id);
}

// 批量删除
export async function batchDelete(ctx) {
  const { ids } = ctx.request.body;
  await batchDeleteQuestions(ids);
  ctx.body = { msg: "ok" };
}